某同学的数据结构作业 - 约瑟夫环变种

Who is the last?(链表实现)

题目描述

There are N people, numbered from 1 to N, sitting around in a circle. Counted from the NO.1, the M.th people should leave the game. Then, from the next one, the counting loop will go on. After several loops, there will be only one guy left. Writing a program to calculate who is the last people.

输入格式

Two integers, separated by commas. The first integer represents n individuals (0<N), the second integer represents M (0<M<=N).

输出格式

N integers, separated by commas. These number indicate the order of the person to leave the circle, with their numbers.

输入样例

5,1

输出样例

2,4,1,5,3

Tips

  • 与约瑟夫环相比,本题计数k由0开始
  • 并将经典约瑟夫环结构去掉密码
  • 取消根据每人手持密码对M的重新赋值操作即可。

Answer

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int no;
	struct node *next;
}Node,*LinkList;

LinkList create_list(int n) ;
void Joseph(LinkList tail, int n, int m) ;
int main(void)
{
	LinkList tailptr;
	int n, m;
	scanf("%d %d",&n,&m);
	tailptr = create_list(n);
	/*创建含有n个结点的单循环链表*/
	if (tailptr)
	{
		Joseph(tailptr, n, m);
	}
	return 0;
}
/*用尾插法创建一个结点数为n的单循环链表,返回值为尾结点的指针*/
LinkList create_list(int n)
{
	LinkList p, rear;
	int i;
	/*先创建循环链表的第一个结点*/
	p = (Node *)malloc(sizeof(Node));
	if (!p) {
		printf("memory allocation error!\n");   return NULL;
	}
	p->no = 1;
	p->next = p;
	rear = p;
	/*创建循环链表的其余n-1个结点*/
	for(i = 2; i <= n; i++)
	{
		p = (Node *)malloc(sizeof(Node));
		if (!p)
		{
			printf("memory allocation error!\n");
			return NULL;
		}
		p->no = i;
		p->next = rear->next;
		rear -> next = p;
		rear = p;
	}
	return rear;
}/* create_list */

void Joseph(LinkList tail, int n, int m)
{
	LinkList pre, p;
	int k;
	m = m % n ? m % n : n;
	pre = tail;
	p = tail -> next;
	k = 0;
	while (n > 1)
	{
		/*圈中多于1个人时循环*/
		if (k == m)
		{
			/*数到需要出去的人(结点)时进行出圈处理*/
			printf("%d", p->no);
			/*p指向的结点为需要删除的结点*/
			pre -> next = p -> next;
			n--;
			free(p);
			p = pre -> next;
			k = 0;
		}
		else
		{
			k++;
			pre = p;
			p = p->next;
		}
	}/*while*/
	printf("%d\n", p->no);
}/*Joseph*/

posted @ 2017-10-22 16:21  VanLion  阅读(297)  评论(0编辑  收藏  举报